const app = getApp();
const API_URL = app.globalData.API_URL;


Page({
  data: {
    customBar: app.globalData.CustomBar,
    ROOT_URL: app.globalData.ROOT_URL,
    Lang:app.globalData.Lang,
    tab: 0,
    current: 0,
    title: [
      "سەھەر ئۈندىدار ئەپچىسى",
      "مال ھارۋىسى",
      "مېنىڭ",
    ],
    cardCur: 0,
    favorCount: 0,
    seenCount: 0,
    count: 1,
    userName: null,
    Modal:false,
    allAmount:0,
    allCount:0,
    peymentSuccess:false,
    clicked:false,
    curLang:null
  },

  onLoad: function (options) {
    let that = this;
    let lang = wx.getStorageSync('lang');
    if(lang){
      this.setData({
        curLang:lang,
      })
    }
    let openid = wx.getStorageSync('openid');
    if (openid) {
      wx.request({
        url: API_URL + 'login',
        method: "POST",
        data: {
          'openid': openid
        },
        success(res) {
          app.globalData.userInfo = res.data.data;
          that.setData({
            userInfo: res.data.data,
          })
        }
      })
    }

    // 获取首页轮播信息
    wx.request({
      url: API_URL + "getSwipers",
      method: 'POST',
      success(res) {
        that.setData({
          swiperList: res.data.data,
        })
      }
    })

    // 获取首页产品类别信息
    wx.request({
      url: API_URL + "getTypes",
      method: 'POST',
      success(res) {
        that.setData({
          types: res.data.data,
        })
      }
    })

    // 获取首页产品信息
    wx.request({
      url: API_URL + "getProducts",
      method: 'POST',
      success(res) {
        that.setData({
          products: res.data.data,
        })
      }
    })
  },

  onShow: function () {
    // 获取所有全局信息
    let that = this;
    let openid = wx.getStorageSync('openid');
    if (openid) {
      wx.request({
        url: API_URL + "getAllinfos",
        method: 'POST',
        data: {
          'openid': openid
        },
        success(res) {
          that.setData({
            favorCount: res.data.data.favorCount,
            seenCount: res.data.data.seenCount,
          });
        }
      })
    }

    let cart = wx.getStorageSync('cart');
    let allCount = 0;

    if (cart && cart!=[]) {
      cart.forEach((item)=>{
        allCount += item.count;
      })
      this.setData({
        allCount:allCount
      })
      let cartList = [];
      cart.forEach((item)=>{
        cartList.push(item.proid);
      });
      wx.request({
        url: API_URL + "getCarProduct",
        method: 'POST',
        data: {'cartList':cartList},
        success(res) {
          let allAmount = 0;
          cart.forEach((item)=>{
            res.data.data.forEach((pro)=>{
              if(item.proid==pro.id){
                pro['count'] = item.count;
                allAmount += (item.count * pro.price);
              }
            })
          });
          that.setData({
            cartListPro: res.data.data,
            allAmount:allAmount,
          })
        }
      })
    }
  },

  getUserInfo: function (e) {
    let that = this;
    wx.getUserProfile({
      desc: '请求授权获取用户信息',
      success(res) {
        let avatarUrl = res.userInfo.avatarUrl;
        let nickName = res.userInfo.nickName;
        wx.login({
          success(res1) {
            let code = res1.code;
            wx.request({
              url: API_URL + 'login',
              method: "POST",
              data: {
                'code': code,
                'avatarUrl': avatarUrl,
                'nickName': nickName
              },
              success(res2) {
                app.globalData.userInfo = res2.data.data;
                wx.setStorageSync('openid', res2.data.data.openid);
                that.setData({
                  userInfo: res2.data.data,
                })
              }
            })
          }
        })
      },
      fail(res) {

      }
    })
  },

  changeTab: function (e) {
    let current = e.detail.current;
    let tab = e.currentTarget.dataset.tab;
    if (tab == null) {
      tab = current;
    }
    this.setData({
      tab: tab,
      current: tab,
    })
  },

  // cardSwiper
  cardSwiper(e) {
    this.setData({
      cardCur: e.detail.current
    })
  },

  payment() {
    let that = this;
    let openid = wx.getStorageSync('openid');
    if (that.data.userName) {
      this.setData({
        clicked:true,
      });
      wx.request({
        url: API_URL + "submitOrder",
        method: 'POST',
        data: {
          'openid': openid,
          'proid': that.data.product.id,
          'count': that.data.count,
          'username': that.data.userName,
          'tel': that.data.telNum,
          'adds': that.data.userAds,
        },
        success(res) {
          let data = res.data;
          data['success'] = () => {
            console.log('微信支付成功');
          };
          data['fail'] = () => {
            console.log('微信支付失败');
          };
          wx.requestPayment(data);
        }
      })
    } else {
      console.log("请选择地址");
    }
  },

  addCount(e) {
    let id = e.currentTarget.dataset.id;
    let cartProList = this.data.cartListPro;
    let allAmount = this.data.allAmount;
    let allCount = this.data.allCount;
    allCount++;
    cartProList.forEach((item)=>{
      if(item.id==id){
        item.count ++;
        allAmount += item.price;
      }
    })
    this.setData({
      cartListPro: cartProList,
      allAmount:allAmount,
      allCount:allCount,
    })
    let cart = wx.getStorageSync('cart');
    cart.forEach((item)=>{
      if(item.proid==id){
        item.count ++;
      }
    })
    wx.setStorageSync('cart', cart)
  },

  subCount(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    let cartProList = this.data.cartListPro;
    let allAmount = this.data.allAmount;
    let allCount = this.data.allCount;
    cartProList.forEach((item)=>{
      if(item.id==id){
        if(item.count>1){
          item.count--;
          allCount--;
          allAmount -= item.price;
        }else if(item.count==1){
          that.setData({
            Modal:true,
            deleteId:item.id,
          })
        }
      }
    })
    this.setData({
      cartListPro: cartProList,
      allAmount:allAmount,
      allCount:allCount,
    })

    let cart = wx.getStorageSync('cart');
    cart.forEach((item)=>{
      if(item.proid==id){
        if(item.count>1){
          item.count--;
        }
      }
    })
    wx.setStorageSync('cart', cart)
  },

  hideModal(e) {
    this.setData({
      Modal: false,
      peymentSuccess:false,
    })
  },

  deleteCart(){
    let id = this.data.deleteId;
    let allAmount = this.data.allAmount;
    let allCount = this.data.allCount;
    allCount--;
    let cartProList = this.data.cartListPro;
    cartProList.forEach((item)=>{
      if(item.id==id){
        allAmount -= item.price;
      }
    })
    cartProList = cartProList.filter((item)=>item.id!=id)
    this.setData({
      cartListPro:cartProList,
      allAmount:allAmount,
      allCount:allCount,
    })

    let cart = wx.getStorageSync('cart');
    cart = cart.filter((item)=>item.proid!=id)
    wx.setStorageSync('cart', cart);
  },

  selectAds() {
    let that = this;
    wx.chooseAddress({
      success: (result) => {
        console.log(result);
        that.setData({
          userName: result.userName,
          telNum: result.telNumber,
          userAds: result.provinceName + result.cityName + result.countyName + result.detailInfo,
        });
      },
    })
  },

  payment(){
    let that = this;
    let openid = wx.getStorageSync('openid');
    let cart = wx.getStorageSync('cart');
    if(that.data.userName && openid){
      wx.request({
        url: API_URL + "submitOrder",
        method: 'POST',
        data: {
          'openid':openid,
          'cart':cart,
          'username': that.data.userName,
          'tel':that.data.telNum,
          'adds':that.data.userAds,
        },
        success(res) {
          let data = res.data;
          data['success'] = ()=>{
            console.log('微信支付成功');
            wx.removeStorageSync('cart');
            that.setData({
              cartListPro:[],
              peymentSuccess:true,
              allAmount:0,
              allCount:0,
            })
          };
          data['fail'] = ()=>{
            console.log('微信支付失败');
          };
          wx.requestPayment(data);
        }
      })
    }else{
      console.log("请选择地址");
    }
  },

  chooseLang(e){
    let lang = e.currentTarget.dataset.lang;
    this.setData({
      curLang:lang,
    })
    wx.setStorageSync('lang', lang)
  },

  changeLang(){
    let lang = wx.getStorageSync('lang');
    if(lang=="UY"){
      this.setData({
        curLang:"CH",
      })
      wx.setStorageSync('lang', "CH");
    }else{
      this.setData({
        curLang:"UY",
      })
      wx.setStorageSync('lang', "UY");
    }
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})